package com.atguigu.gmall.cart.listerner;

import com.atguigu.gmall.cart.mapper.CartInfoMapper;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.rabbit.constant.MqConst;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: 李旭
 * @Time: 14:25
 * @Description:
 *   接收MQ的消息  更新ES索引库
 *
 */

@Component
public class ConsumerUpdateEs {


    @Autowired
    private CartInfoMapper cartInfoMapper;

    //删除购物车
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_CRATE_DELETE,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_CRATE),
            key = MqConst.ROUTING_CRATE_DELETE
    ))
    public void upperGoods(Long userId, Message message, Channel channel){
        try {
            //更新或添加Es
            cartInfoMapper.delete(new QueryWrapper<CartInfo>()
                    .eq("user_id", userId)
                    .eq("is_checked", CartInfo.ISCHECKED));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //e.printStackTrace();
            if(!message.getMessageProperties().isRedelivered()){
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                            false,true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }else{
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),
                            false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}
